﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Model;
using IMClient.View;

namespace IMClient.ViewModels
{
    public partial class ChatWindowViewModel : ObservableObject
    {
        [ObservableProperty] 
        private string userAvatar =User.UserAvatar;

        [ObservableProperty] 
        private string userName =User.UserName;

        [ObservableProperty]
        private string userId = User.UserId;

        // 使用 Lazy<T> 进行懒加载, 确保在第一次使用时才创建实例
        private static readonly Lazy<ChatWindowViewModel> _lazyInstance =
            new Lazy<ChatWindowViewModel>(() => new ChatWindowViewModel());

        // 提供静态属性以获取单例实例
        public static ChatWindowViewModel Instance => _lazyInstance.Value;

        // 私有化构造函数
        private ChatWindowViewModel()
        {
            UserAvatarPath = User.UserAvatar;
            _chatPageViewModel = new ChatPageViewModel();
            _contactsPageViewModel = new ContactsPageViewModel();
            CurrentPage = new ChatView { DataContext = _chatPageViewModel };
        }

        private readonly ChatPageViewModel _chatPageViewModel;
        private readonly ContactsPageViewModel _contactsPageViewModel;

        [ObservableProperty] public string? userAvatarPath;

        [ObservableProperty] private object? currentPage;

        [RelayCommand]
        public void NavigateToChat()
        {
            // 判断 CurrentPage 是否为 ChatView，如果不是则创建新的 ChatView 并设置数据上下文
            CurrentPage = CurrentPage is ChatView 
                ? CurrentPage 
                : new ChatView { DataContext = _chatPageViewModel };
        }

        [RelayCommand]
        public void NavigateToContacts()
        {
            if (!(CurrentPage is ContactsView))
            {
                CurrentPage = new ContactsView { DataContext = _contactsPageViewModel };
            }

            // 调用第二个类的 ShowFriends 方法
            _contactsPageViewModel.ShowFriendsCommand.Execute(null);
        }

        public ChatPageViewModel? GetChatPageViewModel()
        {
            return Instance._chatPageViewModel;
        }

        public ContactsPageViewModel? GetContactsViewModel()
        {
            return Instance._contactsPageViewModel;
        }

        [RelayCommand]
        public void ShowUserDetail()
        {
            var mousePosition = System.Windows.Input.Mouse.GetPosition(System.Windows.Application.Current.MainWindow);

            var detailWindow = new UserDetailWindow
            {
                DataContext = new
                {
                    Avatar = UserAvatar,
                    Name = UserName,
                    Id = $"用户id:{UserId}"
                }
            };

            detailWindow.Left = System.Windows.Application.Current.MainWindow.Left + mousePosition.X;
            detailWindow.Top = System.Windows.Application.Current.MainWindow.Top + mousePosition.Y;

            detailWindow.Show();
        }

    }
}